package com.tsinghua.discharge.service.impl;

import com.csvreader.CsvReader;
import com.tsinghua.discharge.common.Const;
import com.tsinghua.discharge.common.ServerResponse;

import com.tsinghua.discharge.dao.*;
import com.tsinghua.discharge.model.*;
import com.tsinghua.discharge.service.FileUploadRecordService;
import com.tsinghua.discharge.service.UploadDataService;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;

@Service
public class UploadDataServiceImpl implements UploadDataService {
    private static final String CSV = ".csv";
    private static final String SUFFIX_2007 = ".xlsx";
    private static final String SUFFIX_2003 = ".xls";
    @Autowired
    FileUploadRecordService fileUploadRecordService;
    @Autowired
    GcamBaseMapper gcamBaseMapper;
    @Autowired
    GcamResultMapper gcamResultMapper;
    @Autowired
    GcamDataMapper gcamDataMapper;
    @Autowired
    RegionMappingMapper regionMappingMapper;
    @Autowired
    GcamMappingMapper gcamMappingMapper;
    @Autowired
    ThuMappingMapper thuMappingMapper;
    @Autowired
    EnergyBaseMapper energyBaseMapper;
    @Autowired
    EnergyProportionMapper energyProportionMapper;
    @Autowired
    SectorMapper sectorMapper;
    @Autowired
    DataDateMapper dataDateMapper;
    @Autowired
    BaseDataMapper baseDataMapper;
    @Autowired
    private PollutantsMapper pollutantsMapper;
    @Autowired
    private  AreaMapper areaMapper;
    @Autowired
    DeleteFileServiceImpl deleteFileService;

    private boolean checkCsvType(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();


        try {
            if (fileName.endsWith(CSV)) {
                return true;

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件格式错误");
        }
        return false;
    }

    public ServerResponse uploadGCAMMapping(MultipartFile file, HttpSession session, String supSector) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Date now = new Date();
        try {
            if (!this.checkCsvType(file)) {
                throw new Exception("文件格式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if(DeleteOrNot!=0){
//            deleteFileService.deleteByFileType(Const.DataType.GCAMMAPPING,supSector,session);
//        }
        try {
            InputStream inputStream = file.getInputStream();
            CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
            // 跳过表头 如果需要表头的话，这句可以忽略
            //reader.readHeaders();
            reader.readRecord();
            String[] judgement = reader.getValues();
            ArrayList<String> yearOfModel = new ArrayList<String>();
            //校验文件格式
            if (judgement[0].equals("supplysector") && judgement[1].equals("subsector")
                    && judgement[2].equals("stub.technology") && judgement[3].equals("THU_agg_sector")) {
                // 逐行读入除表头的数据
                //boolean变量：真假true或者false
                while (reader.readRecord()) {

                    String[] values = reader.getValues();
                    GcamMapping gcamMapping = new GcamMapping();
                    gcamMapping.setResultMapSupsector(supSector);
                    gcamMapping.setResultMapSector(values[0]);
                    gcamMapping.setResultMapSubsector(values[1]);
                    gcamMapping.setResultMapTechnology(values[2]);
                    gcamMapping.setResultMapThuAggSector(values[3]);
                    gcamMapping.setResultMapUser(currentUser.getId());
                    gcamMapping.setResultMapCreateTime(now);

                    if (gcamMappingMapper.selectRepeat(gcamMapping) <= 0) {
                        gcamMappingMapper.insert(gcamMapping);
                    } else {
                        int id = gcamMappingMapper.selectId(gcamMapping);
                        gcamMapping.setResultMapId(id);
                        gcamMappingMapper.updateByPrimaryKey(gcamMapping);
                    }

                }
            } else {
                reader.close();
                return ServerResponse.createByErrorMessage("校验Mapping文件失败");

            }
            //数据取完了，关闭文件
            reader.close();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("读取GCAMMapping文件失败");
        }
        FileUploadRecord fileUploadRecord = new FileUploadRecord();
        fileUploadRecord.setFileType(Const.DataType.GCAMMAPPING);
        fileUploadRecord.setCreateUserId(currentUser.getId());
        fileUploadRecord.setSector(supSector);
        ServerResponse resRecord = fileUploadRecordService.addRecord(file, fileUploadRecord, session);
        if (!resRecord.isSuccess()) {
            return resRecord;
        }
        return ServerResponse.createBySuccessMessage("读取GCAMMapping文件成功");


    }

    /**
     * 上传gcam_base  gcam_data
     *
     * @param file
     * @param session
     * @return
     */
    public ServerResponse uploadModelResult(MultipartFile file, HttpSession session, String supSector) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Date now = new Date();
        try {
            if (!this.checkCsvType(file)) {
                throw new Exception("文件格式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //匹配顶级部门
        if (supSector.equals(Const.SupSector.ELECTRICITY)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("scenario") && judgement[1].equals("region")
                        && judgement[2].equals("technology") && judgement[3].equals("fuel")) {

                    //开始读入
                    for (int i = 4; i < judgement.length - 1; i++) {
                        yearOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        GcamBase gcamBase = new GcamBase();
                        //GcamResult gcamResult=new GcamResult();
                        gcamBase.setGcamScenario(values[0]);
                        gcamBase.setGcamSupSector(supSector);
                        gcamBase.setGcamTechnology(values[2]);
                        gcamBase.setGcamFuel(values[3]);
                        gcamBase.setGcamUnits(values[values.length - 1]);

                        gcamBase.setGcamSector("");//电力部门没有这两个数据 写空
                        gcamBase.setGcamSubSector("");

                        gcamBase.setGcamUser(currentUser.getId());
                        gcamBase.setGcamCreateTime(now);
                        for (int i = 0; i < yearOfModel.size(); i++) {

                            gcamBase.setGcamDate(yearOfModel.get(i));
                            int gcam_id =0;
                            if (gcamBaseMapper.selectRepeat(gcamBase) <= 0) {
                                gcamBaseMapper.insert(gcamBase);

                            }else{
                                gcam_id = gcamBaseMapper.selectId(gcamBase);
                                gcamBase.setGcamId(gcam_id);
                                gcamBaseMapper.updateByPrimaryKey(gcamBase);
                            }
                            GcamResult gcamResult = new GcamResult();

                            int region_map_id = regionMappingMapper.selectRegionId(values[1], currentUser.getId());
                            gcam_id = gcamBaseMapper.selectId(gcamBase);
                            gcamResult.setResultResult(Float.valueOf(values[4 + i]));
                            gcamResult.setResultGcamId(gcam_id);
                            gcamResult.setResultRegionId(region_map_id);
                            gcamResult.setResultUser(currentUser.getId());
                            gcamResult.setResultCreateTime(now);
                            if (gcamResultMapper.selectRepeat(gcamResult) <= 0) {
                                gcamResultMapper.insert(gcamResult);
                            } else {
                                gcamResultMapper.updateByPrimaryKey(gcamResult);
                            }


                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.MODELDATA);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");


            //匹配building类型文件
        } else if (supSector.equals(Const.SupSector.BUILDING)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("scenario") && judgement[1].equals("region")
                        && judgement[2].equals("sector") && judgement[3].equals("input") && judgement[4].equals("technology")) {

                    //开始读入
                    for (int i = 5; i < judgement.length - 1; i++) {
                        yearOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        GcamBase gcamBase = new GcamBase();

                        gcamBase.setGcamScenario(values[0]);
                        gcamBase.setGcamSupSector(supSector);
                        gcamBase.setGcamTechnology(values[4]);
                        gcamBase.setGcamFuel("");
                        gcamBase.setGcamUnits(values[values.length - 1]);
                        gcamBase.setGcamSector(values[2]);
                        gcamBase.setGcamSubSector(values[3]);

                        gcamBase.setGcamUser(currentUser.getId());
                        gcamBase.setGcamCreateTime(now);
                        for (int i = 0; i < yearOfModel.size(); i++) {

                            gcamBase.setGcamDate(yearOfModel.get(i));
                            int gcam_id=0;
                            if (gcamBaseMapper.selectRepeat(gcamBase) <= 0) {
                                gcamBaseMapper.insert(gcamBase);

                            }else{
                                gcam_id = gcamBaseMapper.selectId(gcamBase);
                                gcamBase.setGcamId(gcam_id);
                                gcamBaseMapper.updateByPrimaryKey(gcamBase);
                            }
                            GcamResult gcamResult = new GcamResult();
                            gcam_id = gcamBaseMapper.selectId(gcamBase);
                            int region_map_id = regionMappingMapper.selectRegionId(values[1], currentUser.getId());
                            gcamResult.setResultResult(Float.valueOf(values[5 + i]));
                            gcamResult.setResultGcamId(gcam_id);
                            gcamResult.setResultRegionId(region_map_id);
                            gcamResult.setResultUser(currentUser.getId());
                            gcamResult.setResultCreateTime(now);
                            if (gcamResultMapper.selectRepeat(gcamResult) <= 0) {
                                gcamResultMapper.insert(gcamResult);
                            } else {
                                gcamResultMapper.updateByPrimaryKey(gcamResult);
                            }

                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.MODELDATA);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");


            //匹配TRANSPROT   类型文件
        } else if (supSector.equals(Const.SupSector.TRANSPROT)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("scenario") && judgement[1].equals("region")
                        && judgement[2].equals("sector") && judgement[3].equals("input") && judgement[4].equals("mode")) {

                    //开始读入
                    for (int i = 5; i < judgement.length - 1; i++) {
                        yearOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        GcamBase gcamBase = new GcamBase();
                        //GcamResult gcamResult=new GcamResult();
                        gcamBase.setGcamScenario(values[0]);
                        gcamBase.setGcamSupSector(supSector);
                        gcamBase.setGcamTechnology(values[3]);
                        gcamBase.setGcamFuel("");
                        gcamBase.setGcamUnits(values[values.length - 1]);
                        gcamBase.setGcamSector(values[2]);
                        gcamBase.setGcamSubSector(values[4]);

                        gcamBase.setGcamUser(currentUser.getId());
                        gcamBase.setGcamCreateTime(now);
                        for (int i = 0; i < yearOfModel.size(); i++) {

                            gcamBase.setGcamDate(yearOfModel.get(i));
                            int gcam_id = 0;
                            if (gcamBaseMapper.selectRepeat(gcamBase) <= 0) {
                                gcamBaseMapper.insert(gcamBase);

                            }else {
                                gcam_id = gcamBaseMapper.selectId(gcamBase);
                                gcamBase.setGcamId(gcam_id);
                                gcamBaseMapper.updateByPrimaryKey(gcamBase);
                            }

                            GcamResult gcamResult = new GcamResult();

                            int region_map_id = regionMappingMapper.selectRegionId(values[1], currentUser.getId());
                            gcam_id = gcamBaseMapper.selectId(gcamBase);
                            gcamResult.setResultResult(Float.valueOf(values[5 + i]));
                            gcamResult.setResultGcamId(gcam_id);
                            gcamResult.setResultRegionId(region_map_id);
                            gcamResult.setResultUser(currentUser.getId());
                            gcamResult.setResultCreateTime(now);
                            if (gcamResultMapper.selectRepeat(gcamResult) <= 0) {
                                gcamResultMapper.insert(gcamResult);
                            } else {
                                gcamResultMapper.updateByPrimaryKey(gcamResult);
                            }


                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.MODELDATA);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");
        } else {
            return ServerResponse.createByErrorMessage("文件顶级部门信息不匹配");
        }
    }


    /**
     * 上传地区映射表
     *
     * @param file
     * @param session
     * @return
     */
    public ServerResponse uploadRegionData(MultipartFile file, HttpSession session) {


        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Date now = new Date();
        try {
            if (!this.checkCsvType(file)) {
                throw new Exception("文件格式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            InputStream inputStream = file.getInputStream();

            // 创建CSV读对象 例如:CsvReader(文件路径，分隔符，编码格式);
            CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
            // 跳过表头 如果需要表头的话，这句可以忽略
            reader.readHeaders();
            // 逐行读入除表头的数据
            //boolean变量：真假true或者false
            while (reader.readRecord()) {
                //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                //再将这个string[]放到list容器中存起来
                String[] values = reader.getValues();
                RegionMapping regionMapping = new RegionMapping();
                regionMapping.setRegionMapGcam(values[0]);
                regionMapping.setRegionMapThu(values[1]);
                regionMapping.setRegionMapUserId(currentUser.getId());
                regionMapping.setRegionMapCreateTime(now);
                if (regionMappingMapper.selectRepeat(regionMapping) <= 0) {
                    regionMappingMapper.insert(regionMapping);
                }else{
                    regionMapping.setRegionMapId(regionMappingMapper.selectId(regionMapping));
                    regionMappingMapper.updateByPrimaryKey(regionMapping);
                }

            }
            reader.close();
        } catch (Exception e) {

            return ServerResponse.createByErrorMessage("读取地区文件失败");
        }

        FileUploadRecord uploadRecord = new FileUploadRecord();
        uploadRecord.setFileType(Const.DataType.REGION);
        uploadRecord.setCreateUserId(currentUser.getId());
        ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
        if (!resRecord.isSuccess()) {
            return resRecord;
        }
        return ServerResponse.createBySuccessMessage("读取地区文件成功");
    }


    /**
     * @param file
     * @param session
     * @return
     */
    public ServerResponse uploadThuData(MultipartFile file, HttpSession session, String supSector) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Date now = new Date();
        try {
            if (!this.checkCsvType(file)) {
                throw new Exception("文件格式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //匹配顶级部门
        if (supSector.equals(Const.SupSector.ELECTRICITY)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略（此处跳过两行）
                reader.readHeaders();
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> regionOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Scenario") && judgement[1].equals("Year")
                        && judgement[2].equals("Sector") && judgement[3].equals("Service")
                        && judgement[4].equals("Technology")) {

                    //开始读入
                    for (int i = 5; i < judgement.length - 1; i++) {
                        regionOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        EnergyBase energyBase = new EnergyBase();
                        energyBase.setEnergySupsector(supSector);
                        energyBase.setEnergyScenario(values[0]);
                        energyBase.setEnergyDate(values[1]);
                        energyBase.setEnergySector(values[2]);
                        energyBase.setEnergyService(values[3]);
                        energyBase.setEnergyTechnology(values[4]);
                        //energyBase.setEnergyFuel("");//电力部门没有这个数据 写空
                        energyBase.setEnergyUser(currentUser.getId());
                        energyBase.setEnergyCreateTime(now);
                        for (int i = 0; i < regionOfModel.size(); i++) {

                            int energy_id = 0;
                            if (energyBaseMapper.selectRepeat(energyBase) <= 0) {
                                energyBaseMapper.insert(energyBase);

                            }else{
                                energy_id = energyBaseMapper.selectId(energyBase);
                                energyBase.setEnergyId(energy_id);
                                energyBaseMapper.updateByPrimaryKey(energyBase);
                            }


                            EnergyProportion energyProportion = new EnergyProportion();

                            int region_map_id = regionMappingMapper.selectTHURegionId(regionOfModel.get(i), currentUser.getId());
                            energy_id = energyBaseMapper.selectId(energyBase);
                            energyProportion.setPropEnergyId(energy_id);
                            energyProportion.setPropRegionId(region_map_id);
                            energyProportion.setPropUser(currentUser.getId());
                            energyProportion.setPropProp(Float.parseFloat(values[5 + i]));
                            energyProportion.setPropCreateTime(now);
                            if (energyProportionMapper.selectRepeat(energyProportion) <= 0) {
                                energyProportionMapper.insert(energyProportion);
                            } else {
                                energyProportionMapper.updateByPrimaryKey(energyProportion);
                            }
                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_PROP);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");


            //匹配building类型文件
        } else if (supSector.equals(Const.SupSector.BUILDING)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                reader.readHeaders();
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> regionOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Scenario") && judgement[1].equals("Year")
                        && judgement[2].equals("Sector") && judgement[3].equals("Service")
                        && judgement[4].equals("Technology")) {

                    //开始读入
                    for (int i = 5; i < judgement.length - 1; i++) {
                        regionOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        EnergyBase energyBase = new EnergyBase();
                        energyBase.setEnergySupsector(supSector);
                        energyBase.setEnergyScenario(values[0]);
                        energyBase.setEnergyDate(values[1]);
                        energyBase.setEnergySector(values[2]);
                        energyBase.setEnergyService(values[3]);
                        energyBase.setEnergyTechnology(values[4]);
                        //energyBase.setEnergyFuel();//建筑部门没有这个数据 写空
                        energyBase.setEnergyUser(currentUser.getId());
                        energyBase.setEnergyCreateTime(now);
                        for (int i = 0; i < regionOfModel.size(); i++) {

                            int energy_id = 0;
                            if (energyBaseMapper.selectRepeat(energyBase) <= 0) {
                                energyBaseMapper.insert(energyBase);

                            }else{
                                energy_id = energyBaseMapper.selectId(energyBase);
                                energyBase.setEnergyId(energy_id);
                                energyBaseMapper.updateByPrimaryKey(energyBase);
                            }


                            EnergyProportion energyProportion = new EnergyProportion();

                            int region_map_id = regionMappingMapper.selectTHURegionId(regionOfModel.get(i), currentUser.getId());
                            energy_id = energyBaseMapper.selectId(energyBase);
                            energyProportion.setPropEnergyId(energy_id);
                            energyProportion.setPropRegionId(region_map_id);
                            energyProportion.setPropUser(currentUser.getId());
                            energyProportion.setPropProp(Float.parseFloat(values[5 + i]));
                            energyProportion.setPropCreateTime(now);
                            if (energyProportionMapper.selectRepeat(energyProportion) <= 0) {
                                energyProportionMapper.insert(energyProportion);
                            } else {
                                energyProportionMapper.updateByPrimaryKey(energyProportion);
                            }
                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_PROP);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");


            //匹配TRANSPROT   类型文件
        } else if (supSector.equals(Const.SupSector.TRANSPROT)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                reader.readHeaders();
                reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> regionOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Scenario") && judgement[1].equals("Year")
                        && judgement[2].equals("Sector") && judgement[3].equals("Service")
                        && judgement[4].equals("Technology") && judgement[5].equals("Fuel")) {

                    //开始读入
                    for (int i = 6; i < judgement.length - 1; i++) {
                        regionOfModel.add(judgement[i]);
                    }
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {
                        //将一行的字符串按照“，”逗号分成多列，存放到String[]数组中
                        //再将这个string[]放到list容器中存起来
                        String[] values = reader.getValues();
                        EnergyBase energyBase = new EnergyBase();
                        energyBase.setEnergySupsector(supSector);
                        energyBase.setEnergyScenario(values[0]);
                        energyBase.setEnergyDate(values[1]);
                        energyBase.setEnergySector(values[2]);
                        energyBase.setEnergyService(values[3]);
                        energyBase.setEnergyTechnology(values[4]);
                        energyBase.setEnergyFuel(values[5]);
                        energyBase.setEnergyUser(currentUser.getId());
                        energyBase.setEnergyCreateTime(now);
                        for (int i = 0; i < regionOfModel.size(); i++) {

                            int energy_id = 0;
                            if (energyBaseMapper.selectRepeat(energyBase) <= 0) {
                                energyBaseMapper.insert(energyBase);

                            }else{
                                energy_id = energyBaseMapper.selectId(energyBase);
                                energyBase.setEnergyId(energy_id);
                                energyBaseMapper.updateByPrimaryKey(energyBase);
                            }


                            EnergyProportion energyProportion = new EnergyProportion();

                            int region_map_id = regionMappingMapper.selectTHURegionId(regionOfModel.get(i), currentUser.getId());
                            energy_id = energyBaseMapper.selectId(energyBase);
                            energyProportion.setPropEnergyId(energy_id);
                            energyProportion.setPropRegionId(region_map_id);
                            energyProportion.setPropUser(currentUser.getId());
                            energyProportion.setPropProp(Float.parseFloat(values[6 + i]));
                            energyProportion.setPropCreateTime(now);
                            if (energyProportionMapper.selectRepeat(energyProportion) <= 0) {
                                energyProportionMapper.insert(energyProportion);
                            } else {
                                energyProportionMapper.updateByPrimaryKey(energyProportion);
                            }

                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("模型文件类型不匹配");
                }
                reader.close();
            } catch (Exception e) {

                return ServerResponse.createByErrorMessage("读取模型文件失败");
            }

            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_PROP);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取模型文件成功");
        } else {
            return ServerResponse.createByErrorMessage("文件顶级部门信息不匹配");
        }
    }

    //上传能源技术映射表
    //上传能源技术映射表
    public ServerResponse uploadThuMapping(MultipartFile file, HttpSession session, String supSector) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Date now = new Date();
        try {
            if (!this.checkCsvType(file)) {
                throw new Exception("文件格式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (supSector.equals(Const.SupSector.ELECTRICITY)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                //reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Sector") && judgement[1].equals("Service")
                        && judgement[2].equals("Tec") && judgement[3].equals("THU_agg_sector")) {
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {

                        String[] values = reader.getValues();

                        ThuMapping thuMapping = new ThuMapping();

                        thuMapping.setPropMapSupsector(supSector);

                        thuMapping.setPropMapSector(values[0]);
                        thuMapping.setPropMapService(values[1]);
                        thuMapping.setPropMapTechnology(values[2]);
                        thuMapping.setPropMapThuAggSector(values[3]);
                        thuMapping.setPropMapUser(currentUser.getId());
                        thuMapping.setPropMapCreateTime(now);
                        if(thuMappingMapper.selectRepeatelc(thuMapping)<=0){
                            thuMappingMapper.insert(thuMapping);
                        }else{
                            int id=thuMappingMapper.selectId(thuMapping);
                            thuMapping.setPropMapId(id);
                            thuMappingMapper.updateByPrimaryKey(thuMapping);
                        }


                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("校验Mapping文件失败");//有bug

                }
                //数据取完了，关闭文件
                reader.close();
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("读取ThuMapping文件失败");
            }
            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_MAPPING);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取能源技术映射表成功");
        } else if (supSector.equals(Const.SupSector.BUILDING)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                //reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Sector") && judgement[1].equals("Service")
                        && judgement[2].equals("Tec") && judgement[3].equals("Fuel") && judgement[4].equals("THU_agg_sector")) {
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {

                        String[] values = reader.getValues();

                        ThuMapping thuMapping = new ThuMapping();

                        thuMapping.setPropMapSupsector(supSector);

                        thuMapping.setPropMapSector(values[0]);
                        thuMapping.setPropMapService(values[1]);
                        thuMapping.setPropMapTechnology(values[2]);
                        thuMapping.setPropMapFuel(values[3]);
                        thuMapping.setPropMapThuAggSector(values[4]);
                        thuMapping.setPropMapUser(currentUser.getId());
                        thuMapping.setPropMapCreateTime(now);
                        if(thuMappingMapper.selectRepeat(thuMapping)<=0){
                            thuMappingMapper.insert(thuMapping);
                        }else{
                            int id=thuMappingMapper.selectId(thuMapping);
                            thuMapping.setPropMapId(id);
                            thuMappingMapper.updateByPrimaryKey(thuMapping);
                        }

                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("校验Mapping文件失败");//有bug
                }
                //数据取完了，关闭文件
                reader.close();
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("读取ThuMapping文件失败");
            }
            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_MAPPING);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取能源技术映射表成功");
        } else if (supSector.equals(Const.SupSector.TRANSPROT)) {
            try {
                InputStream inputStream = file.getInputStream();
                CsvReader reader = new CsvReader(inputStream, ',', Charset.forName("UTF-8"));
                // 跳过表头 如果需要表头的话，这句可以忽略
                //reader.readHeaders();
                reader.readRecord();
                String[] judgement = reader.getValues();
                ArrayList<String> yearOfModel = new ArrayList<String>();
                //校验文件格式
                if (judgement[0].equals("Sector") && judgement[1].equals("Service")
                        && judgement[2].equals("Tec") && judgement[3].equals("Fuel") && judgement[4].equals("THU_agg_sector")) {
                    // 逐行读入除表头的数据
                    //boolean变量：真假true或者false
                    while (reader.readRecord()) {

                        String[] values = reader.getValues();

                        ThuMapping thuMapping = new ThuMapping();

                        thuMapping.setPropMapSupsector(supSector);

                        thuMapping.setPropMapSector(values[0]);
                        thuMapping.setPropMapService(values[1]);
                        thuMapping.setPropMapTechnology(values[2]);
                        thuMapping.setPropMapFuel(values[3]);
                        thuMapping.setPropMapThuAggSector(values[4]);
                        thuMapping.setPropMapUser(currentUser.getId());
                        thuMapping.setPropMapCreateTime(now);
                        if(thuMappingMapper.selectRepeat(thuMapping)<=0){
                            thuMappingMapper.insert(thuMapping);
                        }else{
                            int id=thuMappingMapper.selectId(thuMapping);
                            thuMapping.setPropMapId(id);
                            thuMappingMapper.updateByPrimaryKey(thuMapping);
                        }

                    }
                } else {
                    reader.close();
                    return ServerResponse.createByErrorMessage("校验Mapping文件失败");//有bug

                }
                //数据取完了，关闭文件
                reader.close();
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("读取ThuMapping文件失败");
            }
            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setFileType(Const.DataType.THU_MAPPING);
            uploadRecord.setCreateUserId(currentUser.getId());
            uploadRecord.setSector(supSector);
            ServerResponse resRecord = fileUploadRecordService.addRecord(file, uploadRecord, session);
            if (!resRecord.isSuccess()) {
                return resRecord;
            }
            return ServerResponse.createBySuccessMessage("读取能源技术映射表成功");
        }
      else {
        return ServerResponse.createByErrorMessage("文件顶级部门信息不匹配");
    }
    }


    ///单独展示活动水平
    @Override
    public ServerResponse uploadExcelTech(MultipartFile file, HttpSession session) throws Exception {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        Workbook workbook = this.checkFileType(file);
        if (workbook == null) {
            throw new Exception("文件格式错误");
        }
        int numOfSheet = workbook.getNumberOfSheets();
        for (int i = 0; i < numOfSheet; i++) {
            Sheet sheet = workbook.getSheetAt(i);
            //从sheet中获取sectorLevel和areaLevel
            String sheetName = sheet.getSheetName();
            String[] sheetNames = sheetName.split(",");
            Integer sectorLevel;//部门级别
            Integer areaLevel;
            try{
                sectorLevel = Integer.parseInt(sheetNames[sheetNames.length - 2]);
                areaLevel = Integer.parseInt(sheetNames[sheetNames.length - 1]);
            }catch (Exception e){
                return ServerResponse.createByErrorMessage("sheet命名错误");
            }
            int lastRowNum = sheet.getLastRowNum();
            List<BaseData> techData = new ArrayList<>();
            int dataStart = 7 + sectorLevel;
            Row title = sheet.getRow(0);
            //获取地区ID
            Map<String,Integer> dataCount = new HashMap<>();
            ServerResponse<List<Integer>> res = this.checkRegion(title,dataStart,dataCount,areaLevel,currentUser.getId());
            if(!res.isSuccess()){
                return res;
            }
            int dataEnd = dataCount.get("dataEnd");
            List<Integer> areaIdList = res.getData();
            //从第二行获取数据
            for (int j = 1; j <= lastRowNum; j++) {
                Row row = sheet.getRow(j);
                //将数据中的date数据创建数据库表
                String baseScenario = null;
                Cell cell = row.getCell(0);
                if (checkCell(cell)) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    baseScenario = cell.getStringCellValue();
                }else{
                    baseScenario = "";
                }
                //处理日期数据
                ServerResponse<Integer> response = this.checkDate(row,currentUser);
                if(!response.isSuccess()){
                    return response;
                }
                Integer  baseDateId = response.getData();//插入数据的dataId
                //将数据中sector数据创建数据库表
                response = this.checkSector(row,sectorLevel,currentUser);
                if(!response.isSuccess()){
                    return response;
                }
                Integer baseSectorId = response.getData();
                //处理燃料数据
                cell = row.getCell(4 + sectorLevel);
                String  baseFuel = null;
                if (checkCell(cell)) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    baseFuel = cell.getStringCellValue();
                }
                cell = row.getCell(5 + sectorLevel);
                String unit = null;
                if (checkCell(cell)) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    unit = cell.getStringCellValue();
                }
                //将数据中pollutant数据创建数据库表
                response = this.checkPollutant(6,row,sectorLevel,currentUser);
                if(!response.isSuccess()){
                    return response;
                }
                Integer basePollutantId = response.getData();
                //构造数据
                int count = 0;
                for (int k = dataStart; k <= dataEnd; k++) {
                    Float floatData;
                    cell = row.getCell(k);
                    if (checkCell(cell)) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String data = cell.getStringCellValue();
                        floatData = Float.parseFloat(data);
                    }else{
                        floatData = 0f;
                    }

                    BaseData baseData = new BaseData();
                    baseData.setBaseSectorId(baseSectorId);
                    baseData.setBaseDateId(baseDateId);
                    baseData.setBasePollutantId(basePollutantId);
                    baseData.setBaseScenario(baseScenario);
                    if (!StringUtils.isEmpty( baseFuel)) {
                        baseData.setBaseFuel( baseFuel);
                    }
//                    if (!StringUtils.isEmpty(unit)) {
//                        baseData.setUnit(unit);
//                    }
                    baseData.setBaseTechParam(floatData);
                    Integer baseRegionId= areaIdList.get(count++);
                    baseData.setBaseRegionId(baseRegionId);
                    baseData.setBaseUserId(currentUser.getId());
                    techData.add(baseData);
                }
            }
            for (BaseData item : techData) {
                BaseData hasTech = baseDataMapper.selectByFiveIdsAndSce(item.getBaseScenario(),item.getBaseDateId(),
                        item.getBaseSectorId(), item.getBaseRegionId(), item.getBasePollutantId(),item.getBaseUserId());
                if (hasTech != null) {
                    BaseData updateTech = new BaseData();
                    updateTech.setBaseId(hasTech.getBaseId());
                    updateTech.setBaseSectorId(item.getBaseSectorId());
                    updateTech.setBaseRegionId(item.getBaseRegionId());
                    updateTech.setBasePollutantId(item.getBasePollutantId());
                    updateTech.setBaseDateId(item.getBaseDateId());
                    updateTech.setBaseScenario(item.getBaseScenario());
                    updateTech.setBaseFuel(item.getBaseFuel());
                    //updateTech.setUnit(item.getUnit());
                    updateTech.setBaseTechParam(item.getBaseTechParam());
                    baseDataMapper.updateByPrimaryKeySelective(updateTech);
                } else {
                    baseDataMapper.insert(item);
                }
            }
        }
        //添加文件上传记录
        FileUploadRecord uploadRecord = new FileUploadRecord();
        uploadRecord.setFileType(Const.DataType.TECH);
        uploadRecord.setCreateUserId(currentUser.getId());
        ServerResponse resRecord =  fileUploadRecordService.addXlsxRecord(file,uploadRecord,session);
        if(!resRecord.isSuccess()){
            return resRecord;
        }
        return ServerResponse.createBySuccessMessage("文件上传成功");
    }




    private Workbook checkFileType(MultipartFile file) throws Exception{
        String fileName = file.getOriginalFilename();
        Workbook workbook = null;
        try {
            if (fileName.endsWith(SUFFIX_2003)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (fileName.endsWith(SUFFIX_2007)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件格式错误");
        }
        return workbook;
    }

    private ServerResponse<Integer> checkDate(Row row, User currentUser){
        String year = null;
        Cell cell = row.getCell(1);
        if (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            year = cell.getStringCellValue();
            try{
                String reg = "\\..*";
                year = year.replaceAll(reg,"");
                Integer.parseInt(year);
                if(year.length() != 4){
                    return ServerResponse.createByErrorMessage("日期格式错误");
                }
            }catch (Exception e){
                return ServerResponse.createByErrorMessage("日期格式错误");
            }
        } else {
            ServerResponse.createByErrorMessage("年份不能为空");
        }
        String month = null;
        cell = row.getCell(2);
        if (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            month = cell.getStringCellValue();
            try{
                String reg = "\\..*";
                month = month.replaceAll(reg,"");
                int m = Integer.parseInt(month);
                if(m < 1 || m > 12){
                    return ServerResponse.createByErrorMessage("日期格式错误");
                }
                if(month.length()  == 1){
                    month = "0" + String.valueOf(m);
                }
            }catch (Exception e){
                return ServerResponse.createByErrorMessage("日期格式错误");
            }
        }
        String day = null;
        cell = row.getCell(3);
        if (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            day = cell.getStringCellValue();
            try{
                String reg = "\\..*";
                day = day.replaceAll(reg,"");
                int d = Integer.parseInt(day);
                if(d < 1 || d > 31){
                    return ServerResponse.createByErrorMessage("日期格式错误");
                }
                if(day.length()  == 1){
                    day = "0" + String.valueOf(d);
                }
            }catch (Exception e){
                return ServerResponse.createByErrorMessage("日期格式错误");
            }
        }
        if (StringUtils.isEmpty(year) || (StringUtils.isEmpty(month) && !StringUtils.isEmpty(day))) {
            return ServerResponse.createByErrorMessage("日期格式错误");
        }
        int dateId;//插入数据的dataId
        DataDate currentDate;
        DataDate newDate = new DataDate();
        newDate.setYear(year);
        newDate.setUserId(currentUser.getId());
        if (!StringUtils.isEmpty(day)) {
            newDate.setMonth(month);
            newDate.setDay(month);
            currentDate = dataDateMapper.selectByYearAndMonthAndDay(year, month, day,currentUser.getId());
        } else if (!StringUtils.isEmpty(month)) {
            newDate.setMonth(month);
            currentDate = dataDateMapper.selectByYearAndMonth(year, month,currentUser.getId());
        } else {
            currentDate = dataDateMapper.selectByYear(year,currentUser.getId());
        }
        if (currentDate == null) {
            int affectCount = dataDateMapper.insert(newDate);
            if (affectCount <= 0) {
                return ServerResponse.createByErrorMessage("日期插入失败");
            }
            dateId = newDate.getDateId();
        } else {
            dateId = currentDate.getDateId();
        }
        return ServerResponse.createBySuccess(dateId);
    }

    private ServerResponse<Integer> checkSector(Row row,Integer sectorLevel,User currentUser){
        List<String> supAndSubSector = new ArrayList<>();
        for (int k = 0; k < sectorLevel; k++) {
            Cell cell = row.getCell(k + 4);
            String temp;
            if (checkCell(cell)) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                temp = cell.getStringCellValue();
            } else {
                return ServerResponse.createByErrorMessage("部门不能为空");
            }
            supAndSubSector.add(temp);
            Sector currentSec = sectorMapper.selectAllBySecName(temp, currentUser.getId());
            if (currentSec != null) {
                continue;
            }
            String subSector = temp;
            Sector sector = new Sector();
            sector.setSectorAb(subSector);
            sector.setSectorName(subSector);
            //sector.setSecLevel(k + 1);
            sector.setUserId(currentUser.getId());
            if (k == 0) {
                sector.setSupSectorId(Const.Level.FIRST_LEVEL);
            } else {
                Sector supSec = sectorMapper.selectAllBySecName(supAndSubSector.get(k - 1),currentUser.getId());
                sector.setSupSectorId(supSec.getSectorId());
            }
            int affectedCount = sectorMapper.insert(sector);
            if (affectedCount <= 0) {
                return ServerResponse.createByErrorMessage("插入地区数据失败");
            }
        }
        int secId = sectorMapper.selectAllBySecName(supAndSubSector.get(supAndSubSector.size() - 1),currentUser.getId()).getSectorId();
        return ServerResponse.createBySuccess(secId);
    }

    private ServerResponse<Integer> checkPollutant(int start,Row row,Integer sectorLevel,User currentUser){
        Cell cell = row.getCell(start + sectorLevel);
        String pollutant = null;
        if (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            pollutant = cell.getStringCellValue();
        }
        Integer polId = null;
        Pollutants currentPol;
        if (!StringUtils.isEmpty(pollutant)) {
            currentPol = pollutantsMapper.selectByPollutantAb(pollutant,currentUser.getId());
            if (currentPol == null) {
                Pollutants newPol = new Pollutants();
                newPol.setPollutantab(pollutant);
                newPol.setPollutantname(pollutant);
                newPol.setSuppollutant(Const.Level.FIRST_LEVEL);
                newPol.setUserid(currentUser.getId());
                int affectedCount = pollutantsMapper.insert(newPol);
                if (affectedCount <= 0) {
                    return ServerResponse.createByErrorMessage("插入污染物数据失败");
                }
                polId = newPol.getPolid();
            } else {
                polId = currentPol.getPolid();
            }
        }
        return ServerResponse.createBySuccess(polId);
    }

    private ServerResponse<List<Integer>> checkAreas(Row title, Integer dataStart, Map<String,Integer> dataCount, Integer areaLevel, Integer userId){
        List<String> areas = new ArrayList<>();
        int areaCount = dataStart;
        Cell cell = title.getCell(areaCount);
        while (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String dataArea = cell.getStringCellValue();
            areas.add(dataArea);
            cell = title.getCell(++areaCount);
        }
        int dataEnd = areaCount - 1;
        if (dataEnd < dataStart) {
            return ServerResponse.createByErrorMessage("地区数据有误");
        }
        dataCount.put("dataEnd",dataEnd);
        List<Integer> areaIdList = new ArrayList<>();

        for (int i=0;i<areas.size();i++) {
            //添加China数据
            if(i==0 && StringUtils.equals(Const.CHINA,areas.get(i))){
                Area parent  = areaMapper.selectBySupAreaId(-1,userId);
                if(parent == null){
                    return ServerResponse.createByErrorMessage("请添加国家");
                }
                areaIdList.add(parent.getAreaid());
                continue;
            }
            Area area = areaMapper.selectByAreaAb(areas.get(i),userId);
            if(area == null){
                return ServerResponse.createByErrorMessage("地区不存在，请添加地区数据");
            }
            areaIdList.add(area.getAreaid());
        }
        return ServerResponse.createBySuccess(areaIdList);
    }

    private ServerResponse<List<Integer>> checkRegion(Row title, Integer dataStart, Map<String,Integer> dataCount, Integer areaLevel, Integer userId){

        List<String> areas = new ArrayList<>();
        int areaCount = dataStart;
        Cell cell = title.getCell(areaCount);
        while (checkCell(cell)) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String dataArea = cell.getStringCellValue();
            areas.add(dataArea);
            cell = title.getCell(++areaCount);
        }
        int dataEnd = areaCount - 1;
        if (dataEnd < dataStart) {
            return ServerResponse.createByErrorMessage("地区数据有误");
        }
        dataCount.put("dataEnd",dataEnd);
        List<Integer> areaIdList = new ArrayList<>();

        for (int i=0;i<areas.size();i++) {
            //添加China数据
            if(i==0 && StringUtils.equals(Const.CHINA,areas.get(i))){
                RegionMapping parent  = regionMappingMapper.selectByMap(areas.get(i),userId);
                if(parent == null){
                    return ServerResponse.createByErrorMessage("请添加国家");
                }
                areaIdList.add(parent.getRegionMapId());
                continue;
            }
            RegionMapping area = regionMappingMapper.selectByMap(areas.get(i),userId);
            if(area == null){
                return ServerResponse.createByErrorMessage("地区不存在，请添加地区数据");
            }
            areaIdList.add(area.getRegionMapId());
        }
        return ServerResponse.createBySuccess(areaIdList);

    }

    private boolean checkCell(Cell cell){
        if(cell == null){
            return false;
        }
        cell.setCellType(Cell.CELL_TYPE_STRING);
        String value = cell.getStringCellValue();
        if(StringUtils.isEmpty(value)){
            return false;
        }
        return true;
    }
}